#!/usr/bin/env python
import android,os,time,sys,threading
from subprocess import *

droid = android.Android()

class send(threading.Thread):
	def __init__ (self,x):
		self.x = x
		threading.Thread.__init__ (self)
	def run(self):
		location =self.x
		t=os.system("cat "+location+" | busybox nc "+compip+" 9003")
		if t!=0:
			t=os.system("cat "+location+" | /bin/nc.traditional -w 1 "+compip+" 9003")
		if t!=0:
			t=os.system("cat "+location+" | busybox nc -w 2 "+compip+" 9003")
		if t!=0:
			t=os.system("cat "+location+" | busybox nc -l -p 9003")
def kill():
	a = os.system("test -e /sdcard/sl4a/scripts/kill.sh && echo 'using a fatality'")
	if a !=0:
		str="""kill $(ps | busybox grep 'com.ground.work' | busybox awk '{print $2}') \n su -c "kill -9 $(ps | busybox grep '[p]ython' | busybox awk '{print $2}') \n su -c "ps | busybox grep 'python' | busybox head -1 | busybox cut -d " " -f 4 | busybox xargs kill& ps | busybox grep 'python' | busybox head -1 | busybox cut -d " " -f 4 | busybox xargs kill \n su -c "ps | busybox grep 'python' | busybox head -1 | busybox cut -d " " -f 4 | busybox xargs kill& ps | busybox grep 'com.ground.work' | busybox head -1 | busybox cut -d " " -f 4 | busybox xargs kill"""
		b=open('/sdcard/sl4a/scripts/kill.sh','w').write(str)
	os.system("su -c 'sh /sdcard/sl4a/scripts/kill.sh'")
def quit():
	str="""kill $(ps | busybox grep 'com.ground.work' | busybox awk '{print $2}') \n su -c "kill -9 $(ps | busybox grep '[p]ython' | busybox awk '{print $2}') \n su -c "ps | busybox grep 'python' | busybox head -1 | busybox cut -d " " -f 4 | busybox xargs kill& ps | busybox grep 'python' | busybox head -1 | busybox cut -d " " -f 4 | busybox xargs kill \n su -c "ps | busybox grep 'python' | busybox head -1 | busybox cut -d " " -f 4 | busybox xargs kill& ps | busybox grep 'com.ground.work' | busybox head -1 | busybox cut -d " " -f 4 | busybox xargs kill"""
	b=open('/sdcard/sl4a/scripts/kill.sh','w').write(str)
	os.system("su -c 'sh /sdcard/sl4a/scripts/kill.sh'")
	try:
		print os.system("""su -c "kill -9 $(ps | busybox grep '[p]ython' | busybox awk '{print $2}')" """)
		print os.system("""su -c "kill -9 $(ps | busybox grep 'com.ground.work' | busybox awk '{print $2}')" """)
		app()
	except:
		print os.system("""su -c "ps | busybox grep 'python' | busybox head -1 | busybox cut -d " " -f 4 | busybox xargs kill& ps | busybox grep 'python' | busybox head -1 | busybox cut -d " " -f 4 | busybox xargs kill" """)
		print os.system("""su -c "ps | busybox grep 'python' | busybox head -1 | busybox cut -d " " -f 4 | busybox xargs kill& ps | busybox grep 'com.ground.work' | busybox head -1 | busybox cut -d " " -f 4 | busybox xargs kill" """)
		app()
def resources():
	z=os.system("cd /sdcard/sl4a/scripts && busybox wget http://dl.dropbox.com/u/9283271/GroundWork.zip; mkdir /sdcard/sl4a/scripts/images; mkdir /sdcard/sl4a/scripts/stylesheets; cd /sdcard/sl4a/scripts && busybox unzip -o GroundWork.zip -d /sdcard/sl4a/scripts")
def wifi():
	state= droid.checkWifiState().result
	#print "Is Wifi ON?", state
	if state == False:
		droid.wifiLockAcquireFull()
		droid.toggleWifiState(True)
		time.sleep(15)
		output = Popen("""ifconfig eth0 |grep "inet addr" |awk '{print $2}' |awk -F: '{print $2}'""", shell=True, stdout=PIPE).stdout
		s = output.readlines()
		droid.notify('Device IP Adress', s[0])

	else:
		droid.ttsSpeak('Wifi is already on')
		droid.notify("WIFI STATUS",'ON')
		output = Popen("""ifconfig eth0 |grep "inet addr" |awk '{print $2}' |awk -F: '{print $2}'""", shell=True, stdout=PIPE).stdout
		s = output.readlines()
		droid.notify('Device IP Adress', s)
settings="""
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
	<meta id="viewport" name="viewport" content="width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;">
	<link rel="stylesheet" href="stylesheets/iphone.css">
	<link rel="apple-touch-icon" href="images/apple-touch-icon.png">
	<script type="text/javascript" charset="utf-8">
		var droid = new Android();
		window.onload = function() {
		  setTimeout(function(){window.scrollTo(0, 1);}, 100);
		}
		var save = function() {
		var x = document.getElementById('one').value;
	droid.eventPost("set",x.toString());
		}
</script>
</head>
<body>
<p>
DESKTOP I.P. ADDRESS
</p>
<form NAME='form' method="post" action="save();"> 
<p> <input type="number" maxlength='15' name="IP" size='20' id ="one" placeholder="192.0.0.0" autofocus/> 
</form> 
<div style="-webkit-transition: -webkit-transform .5s ease-in"
  onclick="this.style.webkitTransform='rotate(360deg)'">
<button type="button" style="-webkit-border-radius: 200px;color:red;height=300px;width=500px;" onClick="save();">Save</button>
</div>
</body>
</html>
"""	
def state(phone):
	html="""<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta id="viewport" name="viewport" content="width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;">
	<title>GROUNDWORK</title>
	<link rel="stylesheet" href="stylesheets/iphone.css">
	<link rel="apple-touch-icon" href="images/apple-touch-icon.png">
	<script type="text/javascript" charset="utf-8">
	var droid = new Android();
      window.onload = function() {
		  setTimeout(function(){window.scrollTo(0, 1);}, 100);
		}
      var stop = function() {
        droid.eventPost("off", "off");	
      }
	</script>
	<style type="text/css">
  div.centered{
    display:block;
    position:absolute;
    top:50%;
    left:35%;
    width:350px;
  }
</style>
</head>
<body>
<header>
	<h1>STATUS</h1>
</header>
<article>
<div class="centered">
Running...........
		 <img src="images/run.gif" width='100px' height='100px' title="RUNNING" />	
Running...........
</article>
</div>
</body>
</html>
"""
	a = os.system("test -e /sdcard/sl4a/scripts/run.html && echo 'using saved settings'")
	if a !=0:
		f=open('/sdcard/sl4a/scripts/run.html','w').write(html)
	if phone=="atrix":
		droid.webViewShow('file:///sdcard/sl4a/scripts/run.html')
		os.system('sh /sdcard/sl4a/scripts/'+phone+'frame.sh')
	else:
		droid.webViewShow('file:///sdcard/sl4a/scripts/run.html')
		os.system('su &')
		os.system("start /sdcard/sl4a/scripts/root.sh")
		os.system("su -c 'sh /sdcard/sl4a/scripts/frame.sh'")
		os.system("su -c 'sh /sdcard/sl4a/scripts/frame.sh'")
nexusshtml=""" <html>
  <head>
   <meta charset="utf-8">
	<meta id="viewport" name="viewport" content="width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;">
	<link rel="stylesheet" href="stylesheets/iphone.css">
	<link rel="apple-touch-icon" href="images/apple-touch-icon.png">
    <title>Nexus S</title>
    <script>
      var droid = new Android();
      window.onload = function() {
		  setTimeout(function(){window.scrollTo(0, 1);}, 100);
		}
      var begin = function() {
        droid.eventPost("mode", "one");	
      }
	 var one = function() {
	droid.eventPost("mode","one");
}
 var low = function() {
	droid.eventPost("mode","low");
}
 var medium = function() {
	droid.eventPost("mode","medium");
}
 var high = function() {
	droid.eventPost("mode","high");
}
    </script>
  </head>
  <body>
Fast Network Stream
<p id="slow">
 <button type="button" style="-webkit-border-radius: 200px;color:red;"onClick="one()">Stream</button>
</p>
SLow Network Stream
<p id="slow">
 <button type="button" style="-webkit-border-radius: 200px;color:red;"onClick="low()">Compressed Stream</button>
</p>
<p>
If you can see your browser bar press the back button once!
</p>
</body>
</html>"""
atrixhtml="""
<html>
  <head>
  <meta charset="utf-8">
	<meta id="viewport" name="viewport" content="width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;">
	<link rel="stylesheet" href="stylesheets/iphone.css">
	<link rel="apple-touch-icon" href="images/apple-touch-icon.png">
    <title>ATRIX</title>
    <script>
      var droid = new Android();
      window.onload = function() {
		  setTimeout(function(){window.scrollTo(0, 1);}, 100);
		}
      var begin = function() {
        droid.eventPost("mode", "one");	
      }
	 var one = function() {
	droid.eventPost("mode","one");
}
 var low = function() {
	droid.eventPost("mode","low");
}
 var medium = function() {
	droid.eventPost("mode","medium");
}
 var high = function() {
	droid.eventPost("mode","high");
}
    </script>
  </head>
  <body>
Fast Network Stream
<p id="slow">
 <button type="button" style="-webkit-border-radius: 200px;color:red;"onClick="one()">Stream</button>
</p>
SLow Network Stream
<p id="slow">
 <button type="button" style="-webkit-border-radius: 200px;color:red;"onClick="low()">Compressed Stream</button>
</p>
<p>
If you can see your browser bar press the back button once!
</p>
</body>
</html>
"""
x10html=""" 
<html>
  <head>
   <meta charset="utf-8">
	<meta id="viewport" name="viewport" content="width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;">
	<link rel="stylesheet" href="stylesheets/iphone.css">
	<link rel="apple-touch-icon" href="images/apple-touch-icon.png">
    <title>Xperia X10</title>
    <script>
      var droid = new Android();
      window.onload = function() {
		  setTimeout(function(){window.scrollTo(0, 1);}, 100);
		}
      var begin = function() {
        droid.eventPost("mode", "one");	
      }
	 var one = function() {
	droid.eventPost("mode","one");
}
 var low = function() {
	droid.eventPost("mode","low");
}
 var medium = function() {
	droid.eventPost("mode","medium");
}
 var high = function() {
	droid.eventPost("mode","high");
}
    </script>
  </head>
  <body>
Fast Network Stream
<p id="slow">
 <button type="button" style="-webkit-border-radius: 200px;color:red;"onClick="one()">Stream</button>
</p>
SLow Network Stream
<p id="slow">
 <button type="button" style="-webkit-border-radius: 200px;color:red;"onClick="low()">Compressed Stream</button>
</p>
<p>
If you can see your browser bar press the back button once!
</p>
</body>
</html>"""
start="""
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta id="viewport" name="viewport" content="width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;">
	<title>Choose Your Device</title>
	<link rel="stylesheet" href="stylesheets/iphone.css">
	<link rel="apple-touch-icon" href="images/apple-touch-icon.png">
	<script type="text/javascript" charset="utf-8">
		var droid = new Android();
		window.onload = function() {
		  setTimeout(function(){window.scrollTo(0, 1);}, 100);
		}
		var atrix = function() {
	droid.eventPost("device","atrix");
}
var x10 = function() {
	droid.eventPost("device","x10");
}
var nexuss = function() {
	droid.eventPost("device","nexuss");
}
var wifi = function() {
	droid.eventPost("device","wifion");
}
var help = function() {
	droid.eventPost("device","help");
}
var browse = function() {
	droid.eventPost("device","browse");
}
var configure = function() {
	droid.eventPost("device","settings");
}
var kill = function() {
	droid.eventPost("device","kill");
}
var overkill = function() {
	droid.eventPost("device","overkill");
}
	</script>
</head>
<body>
<header>
	<h1> GROUNDWORK </h1>
<nav> 
<a href="about.html" id="backButton" onclick="help();return true">ABOUT</a> 
</nav> 
</header>
<article>
	<section>
		<h1>CHOOSE YOUR DEVICE</h1>
		<ul>
			<li class="ARROW"><a href="x10.html" onclick="x10()"><img src="images/XperiaX10.jpg" width="100px" height="100" class="ico" /> XPERIA X10 </a></li>
			<li class="arrow"><a href="atrix.html" onclick="atrix();return true"><img src="images/atrix.jpg" width="100px" height="100" class="ico" /> MOTOROLA ATRIX </a></li>
			<li class="arrow"><a href="nexuss.html" onclick="nexuss();return true"><img src="images/nexuss.jpg" width="100px" height="100" class="ico" /> Nexus S</a></li>
		</ul>
		<button type="button" style="-webkit-border-radius: 200px;color:blue;"onClick="wifi()">Turn On Wifi</button>
		<button type="button" style="-webkit-border-radius: 200px;color:blue;"onClick="configure()">Settings</button>
		<button type="button" style="-webkit-border-radius: 200px;color:red;"onClick="kill()">KILL STREAM</button>
		<button type="button" style="-webkit-border-radius: 200px;color:red;"onClick="overkill()">ANNIHILATE</button>
	</section>
</article>
<article>
<section>
<h1> Stream Local Files *experimental*</h1>
<ul>
<li><a href="index.html" onclick="browse();return true">SDCARD</a></li>
</ul>
</section>
</article>
<article>
	<section>
		<h1>HOT BEAT APPS</h1>
		<ul>
			<li class="ARROW"><a href="https://market.android.com/details?id=com.dummy.fooforandroid&feature=search_result"> <img src="images/smsbeast.png" width="30px" height="30" class="ico" /> SMS BROWSER</a></li>
			<li class="arrow"><a href="https://market.android.com/details?id=com.pic.upload&feature=more_from_developer" > <img src="images/auto.png" width="30px" height="30" class="ico" /> AUTO UPLOAD </a></li>
		</ul>
	</section>
</article>
</body>
</html>
"""
load="""
<html>
<body>.....LOADING Images...</body>
</html>
"""
def View(x,tree):
	html="""
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta id="viewport" name="viewport" content="width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;">
	<title>Choose Your Device</title>
	<link rel="stylesheet" href="stylesheets/iphone.css">
	<link rel="apple-touch-icon" href="images/apple-touch-icon.png">
	<script type="text/javascript" charset="utf-8">
		var droid = new Android();
		window.onload = function() {
		  setTimeout(function(){window.scrollTo(0, 1);}, 100);
		}
		var update = function(x) {
	droid.eventPost("update",x);
}
var main = function() {
	droid.eventPost("update","homeindex");
}
var nexuss = function() {
	droid.eventPost("device","nexuss");
}
var wifi = function() {
	droid.eventPost("device","wifion");
}
var help = function() {
	droid.eventPost("device","help");
}
	</script>
</head>
<body>
<header>
	<h1> <a href="index.html" id="backButton" onclick="main();return true">HOME</a> </h1>
</header>
<article>
	<section>
		<ul>
		<li class="ARROW"> <a href="viewer.html" onClick="update('gouponedirectory');return true">..</a></li>
	 """
	for items in x:
		html=html + """<li class="ARROW"> <a href="viewer.html" onClick="update('"""+items.strip()+"""');return true">"""+items.strip()+"""</a></li>""" +'\n'
	html=html+"</ul></nav></section></article></body></html>"	
	open('/sdcard/sl4a/scripts/viewer.html','w').write(html)
	droid.webViewShow('file:///sdcard/sl4a/scripts/viewer.html')	
	while True:
		info=droid.eventWaitFor('update').result
		result=(info['data'])
		if result=="homeindex":
			app()
			break
		elif result=="gouponedirectory":
			back=tree.split('/')
			del back[-1]
			del back[-1]
			del back[0]
			s='/'
			for items in back:
				s=s+items+'/'
			FileBrowse(s)
		else:
			output=Popen("ls "+tree+result+'/',shell=True,stdout=PIPE).stdout
			y=os.system('ls '+tree+result)
			dir=tree + result+'/'
			if str(y)=="0":
				FileBrowse(dir)
			else:
				file(tree+result)
				FileBrowse(tree)
def FileBrowse(place):
	output=Popen("ls "+place,shell=True,stdout=PIPE).stdout
	x=output.readlines()
	y=os.system('ls '+place)
	if str(y)=="0":
		View(x,place)
	else:
		file(place)
def file(x):
	type= x[-4:-1]
	if type=='avi' or type=='mkv' or type=='mp4' or type=="3gp":
		type="video/*"
		#droid.view(x[:-1],type)
		send(x[:-1]).start()
	elif type=='mp3' or type=='aac' or type=='ogg':
		type="audio/*"
		send(x[:-1]).start()
		#droid.view(x[:-1],type)
	else:
		app()
def app():
	droid.webViewShow('file:///sdcard/sl4a/scripts/index.html')
	while True:
		info = droid.eventWaitFor('device').result
		result = (info['data'])
		if result=="settings":
			tx = os.system("test -e /sdcard/sl4a/scripts/config.html && echo 'using saved settings'")
			if tx !=0:
				at=open('/sdcard/sl4a/scripts/config.html','w').write(settings)
			droid.webViewShow('file:///sdcard/sl4a/scripts/config.html')
			while True:
				info = droid.eventWaitFor('set').result
				result = (info['data'])
				print result
				open('/sdcard/sl4a/scripts/settings.txt','w').write(result)
				add="<html> <body><br/> Current Desktop IP ADDRESS: "+result+"</body></html>"
				open('/sdcard/sl4a/scripts/config.html','a').write(add)
				app()
		if result=='browse':
			word='/sdcard/'
			FileBrowse(word)
		if result=='kill':
			quit()
		if result=='overkill':
			kill()
		if result == 'help':
			droid.webViewShow('file:///sdcard/sl4a/scripts/about.html')
			while True:
				info = droid.eventWaitFor('return').result
				result = (info['data'])
				if result == 'return':
					app()
		if result == 'wifion':
			droid.ttsSpeak('Wifo Powering on Pleast Wait')
			wifi()
			app()
		if result == 'atrix':
			atx = os.system("test -e /sdcard/sl4a/scripts/atrix.html && echo 'using saved settings'")
			if atx !=0:
				at=open('/sdcard/sl4a/scripts/atrix.html','w').write(atrixhtml)
			droid.webViewShow('file:///sdcard/sl4a/scripts/atrix.html')
			while True:
				info = droid.eventWaitFor('mode').result
				result = (info['data'])
				if result == 'one':
					droid.ttsSpeak("GroundWork Has Started")
					fb="while true; do fbread | /bin/nc.traditional -w 1 "+compip+" 9000;done"
					p=open('/sdcard/sl4a/scripts/atrixframe.sh','w').write(fb)
					phone="atrix"	
					state(phone)
				if result == 'low':
					droid.ttsSpeak("GroundWork Has Started")
					fb="while true; do (fbread;fbread) | gzip | /bin/nc.traditional -w 1 "+compip+" 9000; done"
					p=open('/sdcard/sl4a/scripts/atrixframe.sh','w').write(fb)
					phone="atrix"	
					state(phone)
		if result == 'x10':
			atx = os.system("test -e /sdcard/sl4a/scripts/x10.html && echo 'using saved settings'")
			if atx !=0:
				at=open('/sdcard/sl4a/scripts/x10.html','w').write(x10html)
			droid.webViewShow('file:///sdcard/sl4a/scripts/x10.html')
			while True:
				info = droid.eventWaitFor('mode').result
				result = (info['data'])
				if result == 'one':
					droid.ttsSpeak("GroundWork Has Started")
					script="while true; do cat /dev/graphics/fb0 | busybox nc "+compip+" 9000;done"
					q=open('/sdcard/sl4a/scripts/frame.sh','w').write(script)
					phone="x10"
					state(phone)
				if result == 'low':
					droid.ttsSpeak("GroundWork Has Started")
					script="while true; do (cat /dev/graphics/fb0;cat /dev/graphics/fb0) | busybox gzip | busybox nc "+compip+" 9000;done"
					q=open('/sdcard/sl4a/scripts/frame.sh','w').write(script)
					phone="x10"
					state(phone)
		if result == 'nexuss':
			atx = os.system("test -e /sdcard/sl4a/scripts/nexuss.html && echo 'using saved settings'")
			if atx !=0:
				at=open('/sdcard/sl4a/scripts/nexuss.html','w').write(nexusshtml)
			droid.webViewShow('file:///sdcard/sl4a/scripts/nexuss.html')
			while True:
				info = droid.eventWaitFor('mode').result
				result = (info['data'])
				if result == 'one':
					droid.ttsSpeak("GroundWork Has Started")
					script="while true; do cat /dev/graphics/fb0 | busybox nc "+compip+" 9000;done"
					q=open('/sdcard/sl4a/scripts/frame.sh','w').write(script)
					phone="nexuss"
					state(phone)
				if result == 'low':
					droid.ttsSpeak("GroundWork Has Started")
					script="while true; do (cat /dev/graphics/fb0;cat /dev/graphics/fb0) | busybox gzip | busybox nc "+compip+" 9000;done"
					q=open('/sdcard/sl4a/scripts/frame.sh','w').write(script)
					phone="nexuss"
					state(phone)
##remove index and old files on new install first run
try:
	p=open('/sdcard/sl4a/scripts/runs.txt','r').readlines()
	p=p[0].strip()
	if p=='1':
		pass
except:
	os.system('rm /sdcard/sl4a/scripts/settings.txt')
	os.system('rm /sdcard/sl4a/scripts/config.html')
	os.system('rm /sdcard/sl4a/scripts/index.html')
	os.system('rm /sdcard/sl4a/scripts/atrix.html')
	os.system('rm /sdcard/sl4a/scripts/x10.html')
	os.system('rm /sdcard/sl4a/scripts/nexuss.html')
	os.system('rm /sdcard/sl4a/scripts/run.html')
	os.system("echo '1' > /sdcard/sl4a/scripts/runs.txt")
##############################################
c = os.system("test -e /sdcard/sl4a/scripts/settings.txt && echo 'using saved settings'")
if c !=0:
	droid.notify('Please','Configure Desktop IP Address in Settings to use GroundWork')	
	compip=''
else:
	r=open('/sdcard/sl4a/scripts/settings.txt','r').readlines()
	print r
	compip=r[0].strip()
a = os.system("test -e /sdcard/sl4a/scripts/images/smsbeast.png && echo 'images exist'")
if a !=0:
	os.system("mkdir /sdcard/sl4a/scripts")
	ld=open('/sdcard/sl4a/scripts/load.html','w').write(load)
	droid.webViewShow('file:///sdcard/sl4a/scripts/load.html')
	resources()
b = os.system("test -e /sdcard/sl4a/scripts/index.html && echo 'index exists'")
if b !=0:
	st=open('/sdcard/sl4a/scripts/index.html','w').write(start)	
app()
